package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.User;
import com.sky.mapper.user.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {

    private final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信接口服务获取 openId
     * @param code
     * @return
     */
    @Override
    public User wxLogin(String code) {
        // 利用 HTTPClient 发送请求获取到微信服务器的响应,根据 response 获取其中的 openId
        String openId = getOpenId(code);
        // 根据 openId 检查是否为新用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, openId));
        if( user == null ){
            // 创建新用户
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        // 返回 User 实体对象
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenId(String code) {
        // 设置请求参数
        HashMap<String, String> query = new HashMap<>();
        query.put("appid", weChatProperties.getAppid());
        query.put("secret", weChatProperties.getSecret());
        query.put("js_code", code);
        query.put("grant_type", "authorization_code");
        // 发送请求
        String response = HttpClientUtil.doGet(WX_LOGIN, query);
        // 解析响应
        JSONObject jsonObject = JSON.parseObject(response);
        String openId = jsonObject.getString("openId");
        return openId;
    }
}
